/**
 * @file   PacketPayload.cpp
 * @author Djuro Drljaca (djurodrljaca@gmail.com)
 * @date   2013-03-10
 * @brief  DataBus Packet Payload.
 *
 * Copyright (C) 2013  Djuro Drljaca <djurodrljaca@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <DataBus/Common/PacketPayload.h>

DataBus::PacketPayload::PacketPayload()
    : m_data()
{
}

DataBus::PacketPayload::PacketPayload(const QByteArray &data)
    : m_data(data)
{
}

QByteArray DataBus::PacketPayload::getData() const
{
    return m_data;
}

void DataBus::PacketPayload::setData(const QByteArray &data)
{
    m_data = data;
}

QByteArray DataBus::PacketPayload::toBinary() const
{
    // Create array
    QByteArray packetData;

    // Add packet data to array
    if (m_data.size() > 0)
    {
        packetData.append(m_data);
        packetData.append(DataBus::calculateChecksum(m_data));
    }

    // Return array
    return packetData;
}

bool DataBus::PacketPayload::parse(const QByteArray &packetPayloadData,
                                   const int startIndex,
                                   const int payloadSize,
                                   PacketPayload *packetPayload)
{
    // Check input parameters
    if ((startIndex < 0) ||
        (startIndex >= packetPayloadData.size()))
    {
        // Error, invalid start index
        return false;
    }

    if ((payloadSize < 0) ||
        ((packetPayloadData.size() - startIndex) < (payloadSize + 1)))
    {
        // Error, data is not big enough
        return false;
    }

    if (packetPayload == 0)
    {
        // Error, null pointer
        return false;
    }

    // Parse header checksum
    quint8 payloadChecksum = (quint8)packetPayloadData.at(startIndex + payloadSize);

    bool ok = false;
    quint8 calculatedChecksum = DataBus::calculateChecksum(packetPayloadData, startIndex, payloadSize, &ok);

    if ((ok == false) ||
        (payloadChecksum != calculatedChecksum))
    {
        // Error, invalid checksum
        return false;
    }

    // Parse payload data
    QByteArray data = packetPayloadData.mid(startIndex, payloadSize);

    // Save values
    packetPayload->setData(data);

    // Success
    return true;
}
